import React, { useState ,useEffect,useRef} from 'react';
import { Search, Grid ,Image,List ,PullRefresh, Tabs, Cell   } from 'react-vant';
import type { ListInstance } from 'react-vant';
import { useDispatch ,useSelector } from 'react-redux';
import { STORETYPE ,ALLLIST,PROPSTYPE} from '../Type/Store.d';
import { useNavigate } from 'react-router-dom';

function IndexChildren() {
    const Navigate = useNavigate();
    const [sindex, setSindex] = useState(0);
    const AllList = useSelector((state:STORETYPE)=>state.list);
    const [NewchildrenList,setNewchildrenList] = useState((AllList[sindex].children as PROPSTYPE[]).slice(0,10));
    const listRef = useRef<ListInstance>(null);
    const [list, setList] = useState<Array<number>>([]);
    const [finished, setFinished] = useState<boolean>(false);
    const [Page,setPage] = useState(1);
    const [isLoading,setisLoading] = useState(false);

     // 上啦加载更多效
    const onLoadRefresh = async() => {
        setisLoading(true)
        setTimeout(() => {
            setPage(Page+1);
            setNewchildrenList((AllList[sindex].children as PROPSTYPE[]).slice(0,10*Page));
            if (NewchildrenList.length >= (AllList[sindex].children as PROPSTYPE[]).length) {
                setFinished(true);
            }
            setisLoading(false)
        }, 2000);
    };
    // 下拉刷新效果
    const onRefresh = async () => {
        setFinished(false);
        setPage(1);
        if(sindex<AllList.length-1){
            setSindex(sindex+1);
        }else{
            setSindex(0);
        }
        
        setNewchildrenList((AllList[sindex].children as PROPSTYPE[]).slice(0,10*Page));
        // console.log(11);
        
    };
    return (
        <div className='IndexChildren'>
            <PullRefresh onRefresh={onRefresh} >
                {/* List 组件可以与 PullRefresh 组件结合使用，实现下拉刷新的效果 */}
                <List ref={listRef} finished={finished} onLoad={onLoadRefresh} loading={isLoading}>
                    <Grid columnNum={2}>
                        {NewchildrenList.map((item, index) => (
                            // 点击商品进入到商品详情
                            <Grid.Item key={index} onClick={()=>Navigate('/Detail/'+item.id,{state:item})}>
                                <Image width="100" height="100" src={item.src} />
                                <p>{item.txt} &emsp;{index+1}</p>
                            </Grid.Item>
                        ))}
                    </Grid>
                </List>
            </PullRefresh>
        </div>
    )
}

export default IndexChildren